import React, { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col } from "antd";
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { useModelAssociateTypeAndMapping} from "@/components";
import cmdbres from "@/data/cmdbres";
import request, {requestIAM} from '@/utils/request';
import regexpUtil from "@/utils/regexpUtil";
import hcpUtils from "@/utils/hcpUtils";

const user = hcpUtils.getUser();
const {filterArray} = hcpUtils;
const CreateServiceTemplate = ({ history, visible, setVisible, onCreateFinish, biz, info }) => {
    const tip = (info && info.id) ? "修改": "新增";
    const [loading, setLoading] = useState(false);
	const [form] = Form.useForm();
    const [bigCategoryData, setBigCategory] = useState([]);
    const [smallCategoryData, setSmallCategory] = useState([]);

    const getCategoryData = async () => {
        try {
            if(!(biz && biz.cm_unid)) {
                message.warning("请确认是否创建业务！");
                return;
            }
            const res = await request({
                ...cmdbres.queryServiceCategory,
                params: {
                    bizId: biz.cm_unid,
                },
            });
            if (res && res.data && res.data.info) {
                const arr = filterArray(res.data.info);
                setBigCategory(arr);
                if(info && info.id) {
                    initUpdateData(arr);
                }
            } else {
                setBigCategory([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        if(visible) {
            getCategoryData();
        }
    }, [visible]);

    const initUpdateData = (arr) => {
        if(!(arr && arr.length)) return;
        let big = null;
        let small = null;
        arr.map(item => {//仅支持二级
            item?.children?.map(child=> {
                if(child.id == info.serviceCategoryId) {
                    small = child;
                    big = item;
                }
            })
        });
        
        console.log(arr, big, small)
        form.setFieldsValue({
            name: info.name,
            bigCategory: big?.id,
            smallCategory: small?.id
        })
        setSmallCategory(big?.children??[]);
    }

	const onFinish = async (fieldsValue) => {
        if(!(biz && biz.cm_unid)) {
			message.warning("请确认是否创建业务！");
			return;
		}
        const {name, smallCategory} = fieldsValue;
        setLoading(true);
        const url = (info && info.id) ? cmdbres.updateServiceTemplate(info.id) : cmdbres.createServiceTemplate;
		let res = await request({
			...url,
			data: {
                bizId: biz.cm_unid,
                name,
                serviceCategoryId: smallCategory,
                author: user.staffName
            }
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success(`${tip}服务模版成功！`);
			if (typeof onCreateFinish == "function") onCreateFinish(res);
		}
	};

    const handleClose = () => {
        setVisible(false);
    }

    return (
        <Drawer 
            className="drawer-table-columns create-field"
            title={`${tip}服务模版`}
            placement={'right'}
            width={600}
            onClose={handleClose}
            visible={visible}
            footer={null}
        >
            <Form
                className="hcp-drawer-form"
                form={form}
                labelCol={{ span: 5}}
                wrapperCol={{ span: 17 }}
                name="basic"
                onFinish={onFinish}
            >
                <Form.Item 
                    label="模板名称" 
                    name="name" 
                    rules={[{required: true,message: '请输入模板名称'}]}
                >
                    <Input placeholder="请输入模板名称" maxLength={64} />
                </Form.Item>
                <Form.Item 
                    label="服务分类 "
                    required
                >
                    <Row gutter={[20, 20]}>
                        <Col span={12}>
                        <Form.Item 
                            name="bigCategory"
                            rules={[{required: true,message: '请选择一级分类'}]}
                        >
                            <Select
                                placeholder="请选择"
                                style={{ width: "100%", marginRight: 10 }}
                                onChange={(value, option) => {
                                    setSmallCategory(option.relation.children||[]);
                                    form.setFieldsValue({smallCategory: undefined});
                                }}
                                showSearch
                            >
                                {
                                    bigCategoryData?.map((item, index) => (
                                        <Select.Option
                                            key={item.id}
                                            value={item.id}
                                            relation={item}
                                        >
                                            {item.name}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                        </Col>
                        <Col span={12}>
                        <Form.Item 
                            name="smallCategory"
                            rules={[{required: true,message: '请选择二级分类'}]}
                        >
                            <Select
                                placeholder="请选择"
                                style={{ width: "100%", marginRight: 10 }}
                                onChange={(value, option) => {

                                }}
                                showSearch
                            >
                                {
                                    smallCategoryData?.map((item, index) => (
                                        <Select.Option
                                            key={item.id}
                                            value={item.id}
                                            relation={item}
                                        >
                                            {item.name}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                        </Col>
                    </Row>
                </Form.Item>
                <div className="modal-body-footer">
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading}>提交</Button>
                        <Button onClick={handleClose}>取消</Button>
                    </Space>
                </div>
            </Form>
        </Drawer>
    );
};

export default CreateServiceTemplate;
